package com.live.activity;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.TextView;

import com.live.common.Constant;
import com.live.common.LiveImageHelper;
import com.live.task.LiveReview;
import com.live.task.LiveScore;

public class LiveDetailActivity extends LiveBaseActivity {

	private Bundle bundle;

	private LiveImageHelper image;

	protected static final int UPDATE_TEXT = 0;

	private LiveReview reviewTask = null;

	public boolean refresh = true;

	private Timer mTimer;
	private TimerTask mTimerTask;
	private Handler mHandler;

	private TabHost tabHost;
	private TabWidget tabWidget;

	private TextView matchName = null;
	private TextView homeTeam = null;
	private TextView homeTeamScore = null;
	private ImageView homeTeamPic = null;
	private TextView visitTeam = null;
	private TextView visitTeamScore = null;
	private ImageView visitTeamPic = null;
	private TextView matchStatus = null;
	private String matchCategory = null;

	public int setTimeout = 60000;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 网络连接判断
		if (netIsOk) {

			setContentView(R.layout.live_detail);

			/* 获取Intent中的Bundle对象 */
			bundle = this.getIntent().getExtras();

			/* 获取Bundle中的数据，注意类型和key */
			matchName = (TextView) findViewById(R.id.matchName);
			homeTeam = (TextView) findViewById(R.id.homeTeam);
			homeTeamScore = (TextView) findViewById(R.id.homeTeamScore);
			homeTeamPic = (ImageView) findViewById(R.id.homeTeamPic);
			visitTeam = (TextView) findViewById(R.id.visitTeam);
			visitTeamScore = (TextView) findViewById(R.id.visitTeamScore);
			visitTeamPic = (ImageView) findViewById(R.id.visitTeamPic);
			matchStatus = (TextView) findViewById(R.id.matchStatus);

			matchName.setText(bundle.getString("matchName"));
			homeTeam.setText(bundle.getString("homeTeam"));
			homeTeamScore.setText(bundle.getString("homeTeamScore"));

			image = new LiveImageHelper(homeTeamPic);
			image.execute(bundle.getString("homeTeamPic"));

			visitTeam.setText(bundle.getString("visitTeam"));
			visitTeamScore.setText(bundle.getString("visitTeamScore"));

			image = new LiveImageHelper(visitTeamPic);
			image.execute(bundle.getString("visitTeamPic"));

			matchStatus.setText(bundle.getString("matchStatus"));

			matchCategory = bundle.getString("matchCategory");

			// 设置刷新时间
			if (matchCategory.equals("1")) {
				// 篮球
				setTimeout = 15000;
			} else if (matchCategory.equals("2") || matchCategory.equals("3")) {
				// 足球
				setTimeout = 60000;
			} else if (matchCategory.equals("6")) {
				// 网球
				setTimeout = 15000;
			} else {
				// 其他
				setTimeout = 15000;
			}

			// 获取TabHost对象
			tabHost = (TabHost) findViewById(R.id.tabhost);

			// 如果没有继承TabActivity时，通过该种方法加载启动tabHost
			tabHost.setup();

			tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("比赛详细").setContent(R.id.scoreList));

			tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("交流论坛").setContent(R.id.view2));

			/* 对Tab标签的定制 */
			tabWidget = tabHost.getTabWidget();

			for (int i = 0; i < tabWidget.getChildCount(); i++) {
				/* 得到每个标签的视图 */
				View view = tabWidget.getChildAt(i);

				/* 设置每个标签的背景 */
				if (tabHost.getCurrentTab() == i) {
					view.setBackgroundDrawable(getResources().getDrawable(R.drawable.listheader_bg));
				} else {
					view.setBackgroundDrawable(getResources().getDrawable(R.drawable.list_bg));
				}

				// 设置标题高度
				((TextView) view.findViewById(android.R.id.title)).setHeight(30);

				/**
				 * 此方法是为了去掉系统默认的色白的底角
				 * 
				 * 在 TabWidget中mBottomLeftStrip、mBottomRightStrip
				 * 都是私有变量，但是我们可以通过反射来获取
				 * 
				 * 由于Android 2.2，2.3的接口不同，加个判断
				 */
				if (Float.valueOf(Build.VERSION.RELEASE.substring(0, 3)) <= 2.1) {
					try {
						Field mBottomLeftStrip = tabWidget.getClass().getDeclaredField("mBottomLeftStrip");
						Field mBottomRightStrip = tabWidget.getClass().getDeclaredField("mBottomRightStrip");
						if (!mBottomLeftStrip.isAccessible()) {
							mBottomLeftStrip.setAccessible(true);
						}
						if (!mBottomRightStrip.isAccessible()) {
							mBottomRightStrip.setAccessible(true);
						}
						mBottomLeftStrip.set(tabWidget, getResources().getDrawable(R.drawable.no));
						mBottomRightStrip.set(tabWidget, getResources().getDrawable(R.drawable.no));

					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					// 如果是2.2,2.3版本开发,可以使用一下方法tabWidget.setStripEnabled(false)
					tabWidget.setStripEnabled(false);
				}

				/* 设置tab的高度 */
				tabWidget.getChildAt(i).getLayoutParams().height = 45;
			}

			/* 当点击Tab选项卡的时候，更改当前Tab标签的背景 */

			tabHost.setOnTabChangedListener(new OnTabChangeListener() {
				public void onTabChanged(String tabId) {

					// 当点击交流论坛的时候
					if ("tab2".equals(tabId)) {
						bundle.putString("type", "select");
						reviewTask = new LiveReview(context, (ListView) findViewById(R.id.reviewList));
						reviewTask.execute(bundle);
					}

					for (int i = 0; i < tabWidget.getChildCount(); i++) {
						View view = tabWidget.getChildAt(i);
						System.out.println(tabHost.getCurrentTab());
						if (tabHost.getCurrentTab() == i) {
							view.setBackgroundDrawable(getResources().getDrawable(R.drawable.listheader_bg));
						} else {
							view.setBackgroundDrawable(getResources().getDrawable(R.drawable.list_bg));
						}
					}
				}
			});

			// 增加读取更多按钮
			/*
			 * LinearLayout listMore = (LinearLayout)
			 * LayoutInflater.from(this).inflate(R.layout.score_list_more,
			 * null); ListView scoreList = (ListView)
			 * findViewById(R.id.scoreList); scoreList.addFooterView(listMore);
			 * 
			 * listMore.setOnClickListener(new View.OnClickListener() {
			 * 
			 * @Override public void onClick(View v) {
			 * 
			 * SimpleAdapter adapter = new SimpleAdapter(context,
			 * liveScoreListAll, R.layout.score_list, new String[] {
			 * "scoreTime", "homeTeamScore", "visitTeamScore", "scoreAction" },
			 * new int[] { R.id.scoreTime, R.id.homeTeamScore,
			 * R.id.visitTeamScore, R.id.scoreAction });
			 * 
			 * scoreList.setAdapter(adapter); } });
			 */

			// 取得比分数据
			LiveScore task = new LiveScore(context, (ListView) findViewById(R.id.scoreList), homeTeamScore,
					visitTeamScore, matchStatus, true);
			task.execute(bundle);

			// 定时刷新比分数据
			if (!"已结束".equals(bundle.getString("matchStatus"))) {
				mHandler = new Handler() {
					@Override
					public void handleMessage(Message msg) {
						switch (msg.what) {
						case UPDATE_TEXT:
							LiveScore task = new LiveScore(context, (ListView) findViewById(R.id.scoreList),
									homeTeamScore, visitTeamScore, matchStatus, false);
							task.execute(bundle);
							break;
						}
					}
				};

				mTimerTask = new TimerTask() {

					@Override
					public void run() {
						Log.d("AndroidTimerDemo", "timer");
						mHandler.sendEmptyMessage(UPDATE_TEXT);
					}
				};

				mTimer = new Timer();
				mTimer.schedule(mTimerTask, setTimeout, setTimeout);// 延时15000ms后执行，15000ms执行一次
			}

			// 发表评论按钮
			Button sendMsgBtn = (Button) findViewById(R.id.sendMsgBtn);
			sendMsgBtn.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {

					// 如果用户已经登录，则可以发表评论
					if (userStatus == Constant.LOGIN) {

						EditText reviewText = (EditText) findViewById(R.id.reviewText);
						if (reviewText.getText().length() != 0) {
							String url = Constant.SITE_URL + "live_review_add.php?";
							url += "matchId=" + bundle.getString("matchId");

							String userId = store.getString("userId", null);
							String userReview = reviewText.getText().toString();
							List<NameValuePair> params = new ArrayList<NameValuePair>();
							params.add(new BasicNameValuePair("reviewUser", userId));
							params.add(new BasicNameValuePair("reviewText", userReview));

							// 添加评论
							if (reviewTask.addMatchReview(url, params)) {

								// 刷新评论列表
								LiveReview task = new LiveReview(context, (ListView) findViewById(R.id.reviewList));
								task.execute(bundle);

								// 清空输入框
								reviewText.setText("");

								// 关闭输入法键盘
								InputMethodManager m = (InputMethodManager) context
										.getSystemService(Context.INPUT_METHOD_SERVICE);
								m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

							}
						}
					} else {
						// 如果用户没有登录，则弹出登录对话框
						userLogin();
					}
				}
			});
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (mTimer != null) {
				mTimer.cancel();
			}
			return super.onKeyDown(keyCode, event);
		}
		return super.onKeyDown(keyCode, event);
	}
}